package org.xxpay.pay.channel.payeasepay.demo;



import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

@SuppressWarnings("restriction")
public class AESfunction {
	
	
    private static String btyeToHex(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs.append("0" + stmp);
            } else {
                hs.append(stmp);
            }
        }
        stmp = null;
        return hs.toString().toUpperCase();
    }

    private static byte[] HexToByte(String hex) {
        byte[] retValue = new byte[(int)(hex.length() / 2)];
        int k = 0;
        for (int i = 0; i < hex.length(); i += 2) {
            retValue[(int)(i / 2)] = (byte)Integer.parseInt(hex.substring(k, i + 2), 16);
            k += 2;
        }
        return retValue;
    }
    public static String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) return null;
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return btyeToHex(bytes);
    }

    public static String aesDecrypt(String hexStr, String key) throws Exception {
        if (hexStr == null || key == null)
            return null;

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        byte[] bytes = HexToByte(hexStr);
        bytes = cipher.doFinal(bytes);
        return new String(bytes, "utf-8");
    }
    
    
  
    
	public static void main(String[] args) throws Exception {
		AESfunction aesfunction = new AESfunction();
		String lsString="ZMgxKVWvOlY2fTxPPInRfTakGt7KZqzavKzf+vtP8udcq0NDXG3561utWmvbeez0/rKH71Ak36oCJSwuHAnEyCcDttCQFwyPZkpvAOiX2nKZSCl4vAq9k2bULzNti/xxac+kU+9pc19Vw5Ux8R1oIxHScJcZM4sU3QwkhevQAukXGlMNt5iYbA/DHNxPM8TPYX/w16JSsTdnbJBh6QYH0hPtRFuoCZ7DWziOStPIxXhagzwTJQ3BbxPDXGSSBKMpzmylqb6qErO6qsJZ8z/Ma1B7kzp52R05Ym0aHLNJKhGT39ZNiG387ChKJ2/xAz9NJIDNyMaBr03FII6mKweOfw==";
		lsString=java.net.URLDecoder.decode(lsString, "UTF-8");
		
		System.out.println("lsString=="+lsString);
		
		String enStr = aesDecrypt(lsString, "MTIzNDU2NzgxMjM0");

		System.out.println(enStr);
			}
}